﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace Administrator
{
    public partial class fImport : Form
    {
        //Типы рисунков узлов дерева типа устройства
        public const Byte ROOT_TYPE = 0;
        public const Byte OBJECT_TYPE = 1;        
        public const Byte DEVICE_TYPE = 2;        
        public const Byte JOIN_TYPE = 3;
        public const Byte CHANNEL_TYPE = 4;
        public const Byte COMMCHAN_TYPE = 5;

        public const Int32 USPD_MIN_MC_COUNT = 256;
        
        private Boolean FormLoaded = false;
        
        //------------------------------------------------------------------------------------
        //Структуры для загрузки из файлов AdminTools
        //------------------------------------------------------------------------------------
        //Настройки типа устройств
        private struct F_DEVICE_SETTING
        {
            public String ModuleDesc;
            public Int32 ProtocolID;
            public Int32 CommChanID;
            public Int32 StorageID;
        }
        //Структура настроек каналов связи и хранилищ данных
        private struct F_MODULE_SETTING
        {
            public Int32 ID;
            public String TypeDescription;
            public String Caption;
            public String Description;
            public Byte[] Setting;//массив байт параметров (максимум 1024 байта)            
        }

        //Информация о тарифе данных измерений устройства
        private struct F_TARIFF_INFO
        {
            public String Caption;
            public Int32 ID;
        }
        //Информация о канале данных измерений устройства
        private struct F_MC_INFO
        {
            public String Caption;
            public Int32 ID;
            public Int32 PQGroup;           //группа физических величин
            public Int32 PQType;            //тип физической величины 
            public Int32 PQMSU;             //кратная или дольная единица физической величины 
            public Int32 DeviceID;         //номер подключенного устройства
            public UInt32 DeviceNetAddress; //адрес подсети подключенного устройства 
            public UInt32 DeviceAddress;    //адрес подключенного устройства  
            public String DeviceIdentifier; //идентификатор подключенного устройства
            public String DeviceSerial;     //заводской номер подключенного устройства
        }
        //Информация о типе данных измерений устройства
        private struct F_DATA_INFO
        {
            public String Caption;
            public Int32 ID;
            public Byte ValType;
            public Byte PeriodType;
            public UInt16 PeriodCount;
            public F_MC_INFO[] MC;
            public F_TARIFF_INFO[] Tariff;
        }
        //Настройки устройства в сети (файл)
        private struct F_DEVICE
        {
            public String UniqueKey;
            public String ModuleDesc;
            public String VersionDesc;
            public String Caption;
            public UInt32 Address;
            public String Identifier;
            public String SerialNumber;
            public String UserName;
            public String UserPass;
            public UInt32 SessionTimeOut;
            public Int32 ProtocolID;
            public Int32 CommChanID;
            public Int32 StorageID;
            public F_DATA_INFO[] Data;
            public int DeviceNumOffset; //Смещение номера счетчика
        }
        //Настройки объекта в сети (файл)
        private struct F_OBJECT
        {
            public String Caption;
            public UInt32 Address;
            public String Identifier;
            public UInt32 ComputerAddress;
            public Int32 CommChanID;
            public Int32 StorageID;
            public F_DEVICE[] Devices;
        }
        //Структура настроек сети (файл)
        private struct F_NETWORK
        {
            public String Caption;
            public F_OBJECT[] Objects;                //Список объектов и устройств
            public F_DEVICE_SETTING[] DeviceSetting;  //Настройки типов устройств
            public F_MODULE_SETTING[] Protocol;       //Список протоколов обмена
            public F_MODULE_SETTING[] CommChan;       //Список каналов связи
            public F_MODULE_SETTING[] Storage;        //Список хранилищ данных                        
        }
        //------------------------------------------------------------------------------------
        private F_NETWORK FNetwork = new F_NETWORK();
        private cMain.OBJECT[] Objects = new cMain.OBJECT[0];
        private Int32 tmpDCIdx = -1;
        
        public fImport()
        {
            InitializeComponent();
        }

        //Заполнение полей
        public void FillFields(Int32 ParentDCIdx)
        {
            FormLoaded = true;

            this.Width = fMain.FormParam[cConst.IMPORT_IDX].WWidth;
            this.Height = fMain.FormParam[cConst.IMPORT_IDX].WHeight;
            if (fMain.FormParam[cConst.IMPORT_IDX].WState == 1)
                this.WindowState = FormWindowState.Maximized;
            else this.WindowState = FormWindowState.Normal;
            this.Left = cMain.MainWindow.Left + (Int32)(cMain.MainWindow.Width / 2) - (Int32)(this.Width / 2);
            this.Top = cMain.MainWindow.Top + (Int32)(cMain.MainWindow.Height / 2) - (Int32)(this.Height / 2);

            tmpDCIdx = ParentDCIdx;

            FormLoaded = false;            
        }
        
        //Заполнение списка меню каналаов связи
        private void FillCommChanItemList(ToolStripMenuItem ParentItem, Int32 ActiveID)
        {
            Int32 i, ActiveIdx;
            ToolStripMenuItem menuItem;

            ActiveIdx = cMain.GetCommChanIndexByID(ActiveID);

            ParentItem.DropDownItems.Clear();
            for (i = 0; i < cMain.CommChanList.Length; i++)
            {
                if (!cMain.CommChanList[i].ItemAction.Deleted)
                {
                    //Добавление пункта типа канала связи
                    menuItem = new ToolStripMenuItem();
                    menuItem.Text = cMain.CommChanList[i].Caption;
                    menuItem.ToolTipText = menuItem.Text;
                    menuItem.Image = imgTree16.Images[COMMCHAN_TYPE];
                    menuItem.Tag = cMain.CommChanList[i].ID.ToString();
                    if (ParentItem == pitmCommChan) 
                        menuItem.Click += pitmCommChan_Click;
                    if (ParentItem == pitmAddCommChan)
                        menuItem.Click += pitmAddCommChan_Click;
                    if (i == ActiveIdx) menuItem.Checked = true;
                    ParentItem.DropDownItems.Add(menuItem);
                }
            }
            ParentItem.Enabled = (ParentItem.DropDownItems.Count > 0);
        }
        //Заполнение списка меню устройств
        private void FillDeviceItemList(ToolStripMenuItem ParentItem,  Int32 ActiveID)
        {
            Int32 i, ActiveIdx;
            ToolStripMenuItem menuItem;

            ActiveIdx = cMain.GetDevTypeIndexByID(ActiveID);
            ParentItem.DropDownItems.Clear();
            for (i = 0; i < cMain.DevTypeList.Length; i++)
            {
                if (!cMain.DevTypeList[i].ItemAction.Deleted)
                {
                    //Добавление пункта типа устройств
                    menuItem = new ToolStripMenuItem();
                    menuItem.Text = cMain.DevTypeList[i].Caption;
                    menuItem.ToolTipText = menuItem.Text;
                    menuItem.Image = imgTree16.Images[DEVICE_TYPE];
                    menuItem.Tag = cMain.DevTypeList[i].ID.ToString();
                    menuItem.Click += pitmDevice_Click;
                    if (i == ActiveIdx) menuItem.Checked = true;
                    ParentItem.DropDownItems.Add(menuItem);
                }
            }
            ParentItem.Enabled = (ParentItem.DropDownItems.Count > 0);
        }
        //Заполнение списка доступных типов счетчика
        private void FillMeterItemList(ToolStripMenuItem ParentItem, Int32 ActiveID)
        {
            Int32 i, ActiveIdx;
            ToolStripMenuItem menuItem;

            ActiveIdx = cMain.GetMeterIndexByID(ActiveID);
            ParentItem.DropDownItems.Clear();
            for (i = 0; i < cMain.MeterList.Length; i++)
            {
                if (!cMain.MeterList[i].ItemAction.Deleted)
                {
                    //Добавление пункта типа счетчика
                    menuItem = new ToolStripMenuItem();
                    menuItem.Text = cMain.MeterList[i].Caption + " (" + cMain.MeterList[i].Precision.ToString("F1") + "/" + cMain.MeterList[i].BeforeComma.ToString() + "." + cMain.MeterList[i].AfterComma.ToString() + "/" + cMain.MeterList[i].MeterConst.ToString() + ")";
                    menuItem.ToolTipText = menuItem.Text;
                    menuItem.Image = imgTree16.Images[CHANNEL_TYPE];
                    menuItem.Tag = cMain.MeterList[i].ID.ToString();
                    menuItem.Click += pitmMeter_Click;
                    if (i == ActiveIdx) menuItem.Checked = true;
                    ParentItem.DropDownItems.Add(menuItem);
                }
            }
            ParentItem.Enabled = (ParentItem.DropDownItems.Count > 0);
        }

        //Заполнение дерева сети из файла
        private void FillNetworkTreeFromFile(String FilePath, TreeView treeView)
        {
            Int32 i, j, k, l, Idx;
            String Caption = "";
            String[] MCDesc = new String[8];
            TreeNode ObjNode, DevNode, JoinNode, ChannelNode;

            treeView.ImageList = imgTree16;
            treeView.Nodes.Clear();
            treeView.Nodes.Add(cConst.NETWORK_CAP);
            treeView.Nodes[0].ImageIndex = ROOT_TYPE;
            treeView.Nodes[0].SelectedImageIndex = ROOT_TYPE;

            if (LoadFileNetworkFromFile(FilePath))
            {
                //Заполнение списка объектов для отображения на базе файла
                FillObjectsList();
                
                treeView.Nodes[0].Text = FNetwork.Caption;
                for (i = 0; i < Objects.Length; i++)
                {
                    //Добавление узла дерева сети
                    ObjNode = new TreeNode(Objects[i].Caption);
                    ObjNode.ImageIndex = OBJECT_TYPE;
                    ObjNode.SelectedImageIndex = OBJECT_TYPE;
                    ObjNode.Tag = i.ToString();
                    for (j = 0; j < Objects[i].Device.Length; j++)
                    {
                        Idx = cMain.GetDevTypeIndexByID(Objects[i].Device[j].DeviceID);
                        if ((Idx >= 0) && (Idx < cMain.DevTypeList.Length))                        
                            Caption = cMain.DevTypeList[Idx].Caption;
                        else Caption = cConst.NONAME_DEVICE_CAPTION;
                        
                        DevNode = new TreeNode(Caption);                        
                        DevNode.ImageIndex = DEVICE_TYPE;
                        DevNode.SelectedImageIndex = DevNode.ImageIndex;
                        DevNode.Tag = j.ToString();
                        for (k = 0; k < Objects[i].Device[j].Join.Length; k++)
                        {
                            JoinNode = new TreeNode(Objects[i].Device[j].Join[k].Caption);
                            JoinNode.ImageIndex = JOIN_TYPE;
                            JoinNode.SelectedImageIndex = JoinNode.ImageIndex;
                            JoinNode.Tag = k.ToString();
                            for (l = 0; l < Objects[i].Device[j].Join[k].Channel.Length; l++)
                            {
                                Caption = cConst.JOIN_ENERGY_TYPE[Objects[i].Device[j].Join[k].Channel[l].EnergyType] + " (";
                                Idx = cMain.GetMeterIndexByID(Objects[i].Device[j].Join[k].Channel[l].MeterID);
                                if ((Idx >= 0) && (Idx < cMain.MeterList.Length))
                                    Caption += cConst.METER_CAPTION_CAP + ": " + cMain.MeterList[Idx].Caption + "; ";
                                else Caption += cConst.METER_CAPTION_CAP + ": " + cConst.METER_NONAME_CAP + "; ";
                                Caption += cConst.CHANNEL_CAPTION_CAP + ": " + (Objects[i].Device[j].Join[k].Channel[l].ID + 1).ToString() + ")"; ;
                                ChannelNode = new TreeNode(Caption);
                                ChannelNode.ImageIndex = CHANNEL_TYPE;
                                ChannelNode.SelectedImageIndex = ChannelNode.ImageIndex;
                                ChannelNode.Tag = l.ToString();
                                JoinNode.Nodes.Add(ChannelNode);
                            }
                            DevNode.Nodes.Add(JoinNode);
                        }
                        ObjNode.Nodes.Add(DevNode);
                    }
                    treeView.Nodes[0].Nodes.Add(ObjNode);
                }
            }
            treeView.SelectedNode = treeView.Nodes[0];
            treeView.Nodes[0].Expand();
        }

        //Очистка полей сети
        private void ResetFileNetwork()
        {
            FNetwork.Caption = cConst.NETWORK_CAP;
            FNetwork.Objects = new F_OBJECT[0];
            FNetwork.DeviceSetting = new F_DEVICE_SETTING[0];
            FNetwork.Protocol = new F_MODULE_SETTING[0];
            FNetwork.CommChan = new F_MODULE_SETTING[0];
            FNetwork.Storage = new F_MODULE_SETTING[0];
        }
        //Загрузка структуры сети из файла в стандарте AdminTools
        private Boolean LoadFileNetworkFromFile(String FilePath)
        {
            Boolean NoError = false;
            StreamReader SReader = null;
            String SettingStr, SWV;
            Int32 i, j, k, a, b, Count;

            if (File.Exists(FilePath))
            {
                try { SReader = File.OpenText(FilePath); }
                catch { SReader = null; }
            }
            if (SReader != null)
            {
                Cursor.Current = Cursors.WaitCursor;

                ResetFileNetwork();
                Objects = new cMain.OBJECT[0]; 
                try
                {
                    SWV = SReader.ReadLine();
                    FNetwork.Caption = SReader.ReadLine();
                    //Загрузка настроек для типов устройств
                    Count = Int32.Parse(SReader.ReadLine());
                    FNetwork.DeviceSetting = new F_DEVICE_SETTING[Count];
                    for (i = 0; i < FNetwork.DeviceSetting.Length; i++)
                    {
                        FNetwork.DeviceSetting[i].ModuleDesc = SReader.ReadLine();
                        FNetwork.DeviceSetting[i].ProtocolID = Int32.Parse(SReader.ReadLine());
                        FNetwork.DeviceSetting[i].CommChanID = Int32.Parse(SReader.ReadLine());
                        FNetwork.DeviceSetting[i].StorageID = Int32.Parse(SReader.ReadLine());
                    }
                    //Загрузка списка протоколов обмена
                    Count = Int32.Parse(SReader.ReadLine());
                    FNetwork.Protocol = new F_MODULE_SETTING[Count];
                    for (i = 0; i < FNetwork.Protocol.Length; i++)
                    {
                        FNetwork.Protocol[i].ID = Int32.Parse(SReader.ReadLine());
                        FNetwork.Protocol[i].TypeDescription = SReader.ReadLine();
                        FNetwork.Protocol[i].Caption = SReader.ReadLine();
                        FNetwork.Protocol[i].Description = SReader.ReadLine();
                        FNetwork.Protocol[i].Setting = new Byte[Int32.Parse(SReader.ReadLine())];
                        SettingStr = SReader.ReadLine();
                        for (j = 0; j < FNetwork.Protocol[i].Setting.Length; j++)
                        {
                            FNetwork.Protocol[i].Setting[j] = Byte.Parse(SettingStr.Substring(0, SettingStr.IndexOf("|")));
                            SettingStr = SettingStr.Substring(SettingStr.IndexOf("|") + 1, SettingStr.Length - SettingStr.IndexOf("|") - 1);
                        }
                    }
                    //Загрузка списка каналов связи
                    Count = Int32.Parse(SReader.ReadLine());
                    FNetwork.CommChan = new F_MODULE_SETTING[Count];
                    for (i = 0; i < FNetwork.CommChan.Length; i++)
                    {
                        FNetwork.CommChan[i].ID = Int32.Parse(SReader.ReadLine());
                        FNetwork.CommChan[i].TypeDescription = SReader.ReadLine();
                        FNetwork.CommChan[i].Caption = SReader.ReadLine();
                        FNetwork.CommChan[i].Description = SReader.ReadLine();
                        FNetwork.CommChan[i].Setting = new Byte[Int32.Parse(SReader.ReadLine())];
                        SettingStr = SReader.ReadLine();
                        for (j = 0; j < FNetwork.CommChan[i].Setting.Length; j++)
                        {
                            FNetwork.CommChan[i].Setting[j] = Byte.Parse(SettingStr.Substring(0, SettingStr.IndexOf("|")));
                            SettingStr = SettingStr.Substring(SettingStr.IndexOf("|") + 1, SettingStr.Length - SettingStr.IndexOf("|") - 1);
                        }
                    }
                    //Загрузка списка хранилищ данных
                    Count = Int32.Parse(SReader.ReadLine());
                    FNetwork.Storage = new F_MODULE_SETTING[Count];
                    for (i = 0; i < FNetwork.Storage.Length; i++)
                    {
                        FNetwork.Storage[i].ID = Int32.Parse(SReader.ReadLine());
                        FNetwork.Storage[i].TypeDescription = SReader.ReadLine();
                        FNetwork.Storage[i].Caption = SReader.ReadLine();
                        FNetwork.Storage[i].Description = SReader.ReadLine();
                        FNetwork.Storage[i].Setting = new Byte[Int32.Parse(SReader.ReadLine())];
                        SettingStr = SReader.ReadLine();
                        for (j = 0; j < FNetwork.Storage[i].Setting.Length; j++)
                        {
                            FNetwork.Storage[i].Setting[j] = Byte.Parse(SettingStr.Substring(0, SettingStr.IndexOf("|")));
                            SettingStr = SettingStr.Substring(SettingStr.IndexOf("|") + 1, SettingStr.Length - SettingStr.IndexOf("|") - 1);
                        }
                    }
                    //Загрузка спиcка объектов
                    Count = Int32.Parse(SReader.ReadLine());
                    FNetwork.Objects = new F_OBJECT[Count];
                    for (i = 0; i < FNetwork.Objects.Length; i++)
                    {
                        FNetwork.Objects[i].Caption = SReader.ReadLine();
                        FNetwork.Objects[i].Address = UInt32.Parse(SReader.ReadLine());
                        FNetwork.Objects[i].Identifier = SReader.ReadLine();
                        FNetwork.Objects[i].ComputerAddress = UInt32.Parse(SReader.ReadLine());
                        FNetwork.Objects[i].CommChanID = Int32.Parse(SReader.ReadLine());
                        FNetwork.Objects[i].StorageID = Int32.Parse(SReader.ReadLine());
                        //Загрузка спика устройств на объекте
                        Count = Int32.Parse(SReader.ReadLine());
                        FNetwork.Objects[i].Devices = new F_DEVICE[Count];
                        for (j = 0; j < FNetwork.Objects[i].Devices.Length; j++)
                        {
                            FNetwork.Objects[i].Devices[j].UniqueKey = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].ModuleDesc = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].VersionDesc = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].Caption = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].Address = UInt32.Parse(SReader.ReadLine());
                            FNetwork.Objects[i].Devices[j].Identifier = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].SerialNumber = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].UserName = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].UserPass = SReader.ReadLine();
                            FNetwork.Objects[i].Devices[j].SessionTimeOut = UInt32.Parse(SReader.ReadLine());
                            FNetwork.Objects[i].Devices[j].ProtocolID = Int32.Parse(SReader.ReadLine());
                            FNetwork.Objects[i].Devices[j].CommChanID = Int32.Parse(SReader.ReadLine());
                            FNetwork.Objects[i].Devices[j].StorageID = Int32.Parse(SReader.ReadLine());
                            FNetwork.Objects[i].Devices[j].DeviceNumOffset = -1;

                            //Загрузка спика данных измерений устройств
                            Count = Int32.Parse(SReader.ReadLine());
                            FNetwork.Objects[i].Devices[j].Data = new F_DATA_INFO[Count];
                            for (k = 0; k < FNetwork.Objects[i].Devices[j].Data.Length; k++)
                            {
                                FNetwork.Objects[i].Devices[j].Data[k].Caption = SReader.ReadLine();
                                FNetwork.Objects[i].Devices[j].Data[k].ID = Int32.Parse(SReader.ReadLine());
                                FNetwork.Objects[i].Devices[j].Data[k].ValType = Byte.Parse(SReader.ReadLine());
                                FNetwork.Objects[i].Devices[j].Data[k].PeriodType = Byte.Parse(SReader.ReadLine());
                                FNetwork.Objects[i].Devices[j].Data[k].PeriodCount = UInt16.Parse(SReader.ReadLine());
                                //Загрузка настроек каналов измерения
                                Count = Int32.Parse(SReader.ReadLine());
                                FNetwork.Objects[i].Devices[j].Data[k].MC = new F_MC_INFO[Count];
                                b = 0;
                                for (a = 0; a < FNetwork.Objects[i].Devices[j].Data[k].MC.Length; a++)
                                {
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].Caption = SReader.ReadLine();
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].ID = Int32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQGroup = Int32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = Int32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQMSU = Int32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].DeviceID = Int32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].DeviceNetAddress = UInt32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].DeviceAddress = UInt32.Parse(SReader.ReadLine());
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].DeviceIdentifier = SReader.ReadLine();
                                    FNetwork.Objects[i].Devices[j].Data[k].MC[b].DeviceSerial = SReader.ReadLine();
                                    if ((FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQGroup == 3) &&
                                        (((FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType >= 1) && (FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType <= 4)) ||
                                         ((FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType >= 85) && (FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType <= 88))))
                                    {
                                        switch (FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType)
                                        { 
                                            case 1:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 0;
                                                break;
                                            case 2:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 1;
                                                break;
                                            case 3:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 2;
                                                break;
                                            case 4:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 3;
                                                break;
                                            case 85:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 4;
                                                break;
                                            case 86:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 5;
                                                break;
                                            case 87:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 6;
                                                break;
                                            case 88:
                                                FNetwork.Objects[i].Devices[j].Data[k].MC[b].PQType = 7;
                                                break;
                                        }
                                        b++;
                                    }
                                }
                                Array.Resize(ref FNetwork.Objects[i].Devices[j].Data[k].MC, b);
                                //Загрузка описания тарифов
                                Count = Int32.Parse(SReader.ReadLine());
                                FNetwork.Objects[i].Devices[j].Data[k].Tariff = new F_TARIFF_INFO[Count];
                                for (a = 0; a < FNetwork.Objects[i].Devices[j].Data[k].Tariff.Length; a++)
                                {
                                    FNetwork.Objects[i].Devices[j].Data[k].Tariff[a].Caption = SReader.ReadLine();
                                    FNetwork.Objects[i].Devices[j].Data[k].Tariff[a].ID = Int32.Parse(SReader.ReadLine());
                                }
                            }
                        }
                    }
                    NoError = true;
                    SReader.Close();
                    FillObjectsList();
                    
                }
                catch
                {
                    SReader.Close();
                    ResetFileNetwork();
                    Objects = new cMain.OBJECT[0]; 
                    NoError = false;
                }
                Cursor.Current = Cursors.Default;
                return NoError;
            }
            else return NoError;
        }
        //Поиск идентификатора в списке объектов учета
        private Boolean FindIDInObjectList(Int32 SearchID)
        {
            Int32 i;
            Boolean Result = false;

            for (i = 0; i < Objects.Length; i++)
            {
                if (Objects[i].ID == SearchID)
                {
                    Result = true;
                    break;
                }
            }
            return Result;
        }       

        //Заполнение рабочего списка объектов
        private void FillObjectsList()
        {
            Int32 i, j, k, a, b, Temp, DeviceID, JoinIdx, ChannelIdx;
            Int32 NewID = 0;   
            
            //Обязательно сделать: добавить проверку уникальности адреса устройства перед добавлением в спиcок

            //Заполнение списка объектов в формате ЦОИ
            Objects = new cMain.OBJECT[FNetwork.Objects.Length];
            for (i = 0; i < Objects.Length; i++)
            {
                cMain.ResetObject(ref Objects[i]);
                //Вычисления уникального идентификатора для Объекта                
                Temp = 0;
                while (true)
                {
                    if ((FindIDInObjectList(Temp)) || 
                        (cMain.FindIDInObjectList(cMain.DC[tmpDCIdx].ID, Temp))) Temp++;
                    else
                    {
                        NewID = Temp;
                        break;
                    }
                }                
                Objects[i].DCID = cMain.DC[tmpDCIdx].ID;
                Objects[i].ID = NewID;
                Objects[i].Caption = FNetwork.Objects[i].Caption;
                Objects[i].ComputerAddress = (Int32)FNetwork.Objects[i].ComputerAddress;                
                Objects[i].Device = new cMain.DEVICE[FNetwork.Objects[i].Devices.Length];
                for (j = 0; j < Objects[i].Device.Length; j++)
                {
                    cMain.ResetDevice(ref Objects[i].Device[j]);
                    Objects[i].Device[j].ID = j;
                    DeviceID = -1;
                    for (k = 0; k < cMain.DevTypeList.Length; k++)
                    {                        
                        if ((!cMain.DevTypeList[k].ItemAction.Deleted) &&
                            (cMain.DevTypeList[k].DeviceDllName == FNetwork.Objects[i].Devices[j].ModuleDesc + ".dll"))
                        {
                            DeviceID = cMain.DevTypeList[k].ID;
                            break;
                        }
                    }                    
                    Objects[i].Device[j].DeviceID = DeviceID;
                    Objects[i].Device[j].NetAddress = (Int32)FNetwork.Objects[i].Address;
                    Objects[i].Device[j].Address = (Int32)FNetwork.Objects[i].Devices[j].Address;
                    Objects[i].Device[j].Identifier = FNetwork.Objects[i].Devices[j].Identifier;
                    Objects[i].Device[j].SerialNumber = FNetwork.Objects[i].Devices[j].SerialNumber;
                    Objects[i].Device[j].UserName = FNetwork.Objects[i].Devices[j].UserName;
                    Objects[i].Device[j].UserPassword = FNetwork.Objects[i].Devices[j].UserPass;
                    Objects[i].Device[j].DeviceNumOffset = FNetwork.Objects[i].Devices[j].DeviceNumOffset;

                    for (k = 0; k < FNetwork.Objects[i].Devices[j].Data.Length; k++)
                    {
                        for (a = 0; a < FNetwork.Objects[i].Devices[j].Data[k].MC.Length; a++)
                        { 
                            JoinIdx = -1;
                            for (b = 0; b < Objects[i].Device[j].Join.Length; b++)
                            {
                                if (Objects[i].Device[j].Join[b].MeterNumber == (Int32)FNetwork.Objects[i].Devices[j].Data[k].MC[a].DeviceID)
                                {                                    
                                    JoinIdx = b;
                                    break;
                                }
                            }
                            if (JoinIdx < 0)
                            {
                                JoinIdx = Objects[i].Device[j].Join.Length;
                                Array.Resize(ref Objects[i].Device[j].Join, JoinIdx + 1);                                
                                cMain.ResetJoin(ref Objects[i].Device[j].Join[JoinIdx]);
                                Objects[i].Device[j].Join[JoinIdx].DeviceID = Objects[i].Device[j].ID;
                                Objects[i].Device[j].Join[JoinIdx].ID = JoinIdx;
                                if (JoinIdx == 0) Objects[i].Device[j].Join[JoinIdx].Caption = cConst.JOIN_CAPTION;
                                else Objects[i].Device[j].Join[JoinIdx].Caption = cConst.JOIN_CAPTION + " (" + Objects[i].Device[j].Join.Length.ToString() + ")";
                                Objects[i].Device[j].Join[JoinIdx].MeterNumber = FNetwork.Objects[i].Devices[j].Data[k].MC[a].DeviceID;                                
                            }                            
                            //Добавление канала учета
                            ChannelIdx = -1;
                            for (b = 0; b < Objects[i].Device[j].Join[JoinIdx].Channel.Length; b++)
                            {
                                if ((Objects[i].Device[j].Join[JoinIdx].Channel[b].ID == FNetwork.Objects[i].Devices[j].Data[k].MC[a].ID) ||
                                    (Objects[i].Device[j].Join[JoinIdx].Channel[b].EnergyType == FNetwork.Objects[i].Devices[j].Data[k].MC[a].PQType))
                                {
                                    ChannelIdx = b;
                                    break;
                                }
                            }
                            if (ChannelIdx < 0)
                            {
                                Array.Resize(ref Objects[i].Device[j].Join[JoinIdx].Channel, Objects[i].Device[j].Join[JoinIdx].Channel.Length + 1);
                                ChannelIdx = Objects[i].Device[j].Join[JoinIdx].Channel.Length - 1;
                                cMain.ResetChannel(ref Objects[i].Device[j].Join[JoinIdx].Channel[ChannelIdx]);
                                Objects[i].Device[j].Join[JoinIdx].Channel[ChannelIdx].ID = FNetwork.Objects[i].Devices[j].Data[k].MC[a].ID;
                                Objects[i].Device[j].Join[JoinIdx].Channel[ChannelIdx].EnergyType = (Byte)FNetwork.Objects[i].Devices[j].Data[k].MC[a].PQType;
                                Objects[i].Device[j].Join[JoinIdx].Channel[ChannelIdx].MeterSerial = FNetwork.Objects[i].Devices[j].Data[k].MC[a].DeviceSerial;
                            }                            
                        }
                    }                                    
                }
            }   
        }
        
        //Проверка полей списка временных объектов для добавления
        private Boolean CheckObjects()
        {
            Int32 i, j, k, l;
            Boolean Result = true;

            for (i = 0; (i < Objects.Length) && (Result); i++)
            {
                if (tvNetwork.Nodes[0].Nodes[i].Checked)
                {
                    if (cMain.GetCommChanIndexByID(Objects[i].CommChan) < 0)
                    {
                        MessageBox.Show(cConst.OBJECT_COMMCHAN_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Result = false;
                    }
                    if (Result)
                    {
                        if (cMain.GetCommChanIndexByID(Objects[i].AddCommChan) < 0)
                        {
                            MessageBox.Show(cConst.OBJECT_ADD_COMMCHAN_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Result = false;
                        }
                    }
                    for (j = 0; (j < Objects[i].Device.Length) && (Result); j++)
                    {
                      
                        if (tvNetwork.Nodes[0].Nodes[i].Nodes[j].Checked)
                        {
                            if (Objects[i].Device[j].DeviceNumOffset == -1)
                            {
                                MessageBox.Show(cConst.ERR_UNK_DEVICENUM_OFFSET, cConst.ERROR_CAPTION,
                                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Result = false;
                            }
                            if (cMain.GetDevTypeIndexByID(Objects[i].Device[j].DeviceID) < 0)
                            {
                                MessageBox.Show(cConst.DEVICE_TYPE_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Result = false;
                            }
                            for (k = 0; (k < Objects[i].Device[j].Join.Length) && (Result); k++)
                            {
                                if (tvNetwork.Nodes[0].Nodes[i].Nodes[j].Nodes[k].Checked)
                                {
                                    if (Objects[i].Device[j].Join[k].MeterNumber < (Objects[i].Device[j].DeviceNumOffset))
                                    {
                                        MessageBox.Show(cConst.ERR_INKOR_DEVICENUM_MORE, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        Result = false;
                                    }

                                    for (l = 0; (l < Objects[i].Device[j].Join[k].Channel.Length) && (Result); l++)
                                    {
                                        if (tvNetwork.Nodes[0].Nodes[i].Nodes[j].Nodes[k].Nodes[l].Checked)
                                        {
                                            if (cMain.GetMeterIndexByID(Objects[i].Device[j].Join[k].Channel[l].MeterID) < 0)
                                            {
                                                MessageBox.Show(cConst.CHANNEL_METER_ERROR_CAP, cConst.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                Result = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }          
            return Result;
        }
        //Экспорт временных объектов в главную структуру сети
        private Boolean AddNewObjectsToNetworkDC(Int32 DCIdx)
        {
            Int32 i, j, k, l, ObjIdx, DevIdx, JoinIdx, ChannelIdx/*, Idx*/;
            Boolean Result = false;

            Result = CheckObjects();
            if (Result)
            {
                for (i = 0; i < Objects.Length; i++)
                {
                    if (tvNetwork.Nodes[0].Nodes[i].Checked)
                    {
                        ObjIdx = cMain.AddNewObject(tmpDCIdx, Objects[i].Caption);
                        cMain.Objects[ObjIdx].ComputerAddress = Objects[i].ComputerAddress;
                        cMain.Objects[ObjIdx].CommChan = Objects[i].CommChan;
                        cMain.Objects[ObjIdx].AddCommChan = Objects[i].AddCommChan;
                        for (j = 0; j < Objects[i].Device.Length; j++)
                        {
                            if (tvNetwork.Nodes[0].Nodes[i].Nodes[j].Checked)
                            {
                                DevIdx = cMain.AddNewDevice(ObjIdx, Objects[i].Device[j].DeviceID);
                                cMain.Objects[ObjIdx].Device[DevIdx].NetAddress = Objects[i].Device[j].NetAddress;
                                cMain.Objects[ObjIdx].Device[DevIdx].Address = Objects[i].Device[j].Address;
                                cMain.Objects[ObjIdx].Device[DevIdx].Identifier = Objects[i].Device[j].Identifier;
                                cMain.Objects[ObjIdx].Device[DevIdx].SerialNumber = Objects[i].Device[j].SerialNumber;
                                cMain.Objects[ObjIdx].Device[DevIdx].UserName = Objects[i].Device[j].UserName;
                                cMain.Objects[ObjIdx].Device[DevIdx].UserPassword = Objects[i].Device[j].UserPassword;
                                for (k = 0; k < Objects[i].Device[j].Join.Length; k++)
                                {
                                    if (tvNetwork.Nodes[0].Nodes[i].Nodes[j].Nodes[k].Checked)
                                    {
                                        JoinIdx = cMain.AddNewJoin(ObjIdx, DevIdx, Objects[i].Device[j].Join[k].Caption);
                                        cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].MeterNumber = Objects[i].Device[j].Join[k].MeterNumber - (Objects[i].Device[j].DeviceNumOffset + 1);
                                        for (l = 0; l < Objects[i].Device[j].Join[k].Channel.Length; l++)
                                        {
                                            if (tvNetwork.Nodes[0].Nodes[i].Nodes[j].Nodes[k].Nodes[l].Checked)
                                            {
                                                ChannelIdx = cMain.AddNewChannel(ObjIdx, DevIdx, JoinIdx, Objects[i].Device[j].Join[k].Channel[l].EnergyType, Objects[i].Device[j].Join[k].Channel[l].MeterID, Objects[i].Device[j].Join[k].Channel[l].ID);
                                                if (cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].MeterSerial == "")
                                                    cMain.Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].MeterSerial = Objects[i].Device[j].Join[k].Channel[l].MeterSerial;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return Result;
        }

        private void fImport_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
                fMain.FormParam[cConst.IMPORT_IDX].WState = 1;
            else fMain.FormParam[cConst.IMPORT_IDX].WState = 0;
        }
        private void fImport_Resize(object sender, EventArgs e)
        {
            if ((!FormLoaded) && (this.WindowState == FormWindowState.Normal))
            {
                fMain.FormParam[cConst.IMPORT_IDX].WWidth = this.Width;
                fMain.FormParam[cConst.IMPORT_IDX].WHeight = this.Height;
                
            }
        }
        
        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
                FillNetworkTreeFromFile(openFileDialog.FileName, tvNetwork);
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (AddNewObjectsToNetworkDC(tmpDCIdx)) 
            {    
                this.DialogResult = DialogResult.OK;
                Close();
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void tvNetwork_MouseDown(object sender, MouseEventArgs e)
        {
            Point APoint = e.Location;
            TreeNode Node;

            if (e.Button == MouseButtons.Right)
            {
                Node = ((TreeView)sender).GetNodeAt(e.Location);
                if (Node != null)
                {
                    ((TreeView)sender).SelectedNode = Node;
                    ((TreeView)sender).Focus();
                    APoint = ((TreeView)sender).PointToScreen(e.Location);
                    cmsNetwork.Show(APoint);
                }
            }
        }

        private void cmsNetwork_Opening(object sender, CancelEventArgs e)
        {
            if ((!FormLoaded) && (tvNetwork.SelectedNode != null))
            {
                pitmCommChan.Visible = (tvNetwork.SelectedNode.ImageIndex == OBJECT_TYPE);
                pitmAddCommChan.Visible = (tvNetwork.SelectedNode.ImageIndex == OBJECT_TYPE);
                pitmDevice.Visible = (tvNetwork.SelectedNode.ImageIndex == DEVICE_TYPE);
                pitmChannelMeter.Visible = (tvNetwork.SelectedNode.ImageIndex == CHANNEL_TYPE);
                pitmJoinMeter.Visible = (tvNetwork.SelectedNode.ImageIndex == JOIN_TYPE);
                pitmDeviceMeter.Visible = (tvNetwork.SelectedNode.ImageIndex == DEVICE_TYPE);
                pitmPulseMetersCount.Visible = (tvNetwork.SelectedNode.ImageIndex == DEVICE_TYPE);

                if (tvNetwork.SelectedNode.ImageIndex == JOIN_TYPE)
                    pitmJoinMeter.Text = cConst.METER_TYPE_FOR_JOIN_CAP;
                else pitmJoinMeter.Text = "";
                if (tvNetwork.SelectedNode.ImageIndex == DEVICE_TYPE)
                    pitmDeviceMeter.Text = cConst.METER_TYPE_FOR_DEVICE_CAP;
                else pitmDeviceMeter.Text = "";

                switch (tvNetwork.SelectedNode.ImageIndex)
                {
                    case OBJECT_TYPE:                
                        FillCommChanItemList(pitmCommChan, Objects[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].CommChan);
                        FillCommChanItemList(pitmAddCommChan, Objects[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].AddCommChan);
                        break;                
                    case DEVICE_TYPE:                
                        FillDeviceItemList(pitmDevice, Objects[Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString())].Device[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].DeviceID);
                        FillMeterItemList(pitmDeviceMeter, -1);
                        break;                                    
                    case JOIN_TYPE:
                        FillMeterItemList(pitmJoinMeter, -1);
                        break;
                    case CHANNEL_TYPE:
                        FillMeterItemList(pitmChannelMeter, Objects[Int32.Parse(tvNetwork.SelectedNode.Parent.Parent.Parent.Tag.ToString())].Device[Int32.Parse(tvNetwork.SelectedNode.Parent.Parent.Tag.ToString())].Join[Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString())].Channel[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].MeterID);
                        break;
                }                
            }
        }
        private void pitmCommChan_Click(object sender, EventArgs e)
        {
            if (tvNetwork.SelectedNode != null)
                Objects[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].CommChan = Int32.Parse(((ToolStripMenuItem)sender).Tag.ToString());
        }
        private void pitmAddCommChan_Click(object sender, EventArgs e)
        {
            if (tvNetwork.SelectedNode != null)
            {
                Objects[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].AddCommChan = Int32.Parse(((ToolStripMenuItem)sender).Tag.ToString());
            }
        }
        private void pitmDevice_Click(object sender, EventArgs e)
        {
            if (tvNetwork.SelectedNode != null)
            {
                Objects[Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString())].Device[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].DeviceID = Int32.Parse(((ToolStripMenuItem)sender).Tag.ToString());
                tvNetwork.SelectedNode.Text = cMain.DevTypeList[cMain.GetDevTypeIndexByID(Objects[Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString())].Device[Int32.Parse(tvNetwork.SelectedNode.Tag.ToString())].DeviceID)].Caption;
            }
        }
        private void pitmMeter_Click(object sender, EventArgs e)
        {
            String Caption = "";
            Int32 i, j, ObjIdx, DevIdx, JoinIdx, ChannelIdx, Idx;

            switch (tvNetwork.SelectedNode.ImageIndex)
            {
                case DEVICE_TYPE:
                    ObjIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString());
                    DevIdx = Int32.Parse(tvNetwork.SelectedNode.Tag.ToString());
                    for (i = 0; i < Objects[ObjIdx].Device[DevIdx].Join.Length; i++)
                    {
                        for (j = 0; j < Objects[ObjIdx].Device[DevIdx].Join[i].Channel.Length; j++)                        
                            Objects[ObjIdx].Device[DevIdx].Join[i].Channel[j].MeterID = Int32.Parse(((ToolStripMenuItem)sender).Tag.ToString());                        
                    }
                    for (i = 0; i < tvNetwork.SelectedNode.Nodes.Count; i++)
                    {
                        JoinIdx = Int32.Parse(tvNetwork.SelectedNode.Nodes[i].Tag.ToString());
                        for (j = 0; j < tvNetwork.SelectedNode.Nodes[i].Nodes.Count; j++)
                        {
                            ChannelIdx = Int32.Parse(tvNetwork.SelectedNode.Nodes[i].Nodes[j].Tag.ToString());

                            Caption = cConst.JOIN_ENERGY_TYPE[Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].EnergyType] + " (";
                            Idx = cMain.GetMeterIndexByID(Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].MeterID);
                            if ((Idx >= 0) && (Idx < cMain.MeterList.Length))
                                Caption += cConst.METER_CAPTION_CAP + ": " + cMain.MeterList[Idx].Caption + "; ";
                            else Caption += cConst.METER_CAPTION_CAP + ": " + cConst.METER_NONAME_CAP + "; ";
                            Caption += cConst.CHANNEL_CAPTION_CAP + ": " + (Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].ID + 1).ToString() + ")"; ;
                            tvNetwork.SelectedNode.Nodes[i].Nodes[j].Text = Caption;
                        }
                    }
                    break;
                case JOIN_TYPE:
                    ObjIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Parent.Tag.ToString());
                    DevIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString());
                    JoinIdx = Int32.Parse(tvNetwork.SelectedNode.Tag.ToString());
                    for (i = 0; i < Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel.Length; i++)                    
                        Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[i].MeterID = Int32.Parse(((ToolStripMenuItem)sender).Tag.ToString());
                    for (i = 0; i < tvNetwork.SelectedNode.Nodes.Count; i++)
                    {
                        ChannelIdx = Int32.Parse(tvNetwork.SelectedNode.Nodes[i].Tag.ToString());
                        
                        Caption = cConst.JOIN_ENERGY_TYPE[Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].EnergyType] + " (";
                        Idx = cMain.GetMeterIndexByID(Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].MeterID);
                        if ((Idx >= 0) && (Idx < cMain.MeterList.Length))
                            Caption += cConst.METER_CAPTION_CAP + ": " + cMain.MeterList[Idx].Caption + "; ";
                        else Caption += cConst.METER_CAPTION_CAP + ": " + cConst.METER_NONAME_CAP + "; ";
                        Caption += cConst.CHANNEL_CAPTION_CAP + ": " + (Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].ID + 1).ToString() + ")"; ;
                        tvNetwork.SelectedNode.Nodes[i].Text = Caption;
                    }
                    break;
                case CHANNEL_TYPE:
                    ObjIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Parent.Parent.Tag.ToString());
                    DevIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Parent.Tag.ToString());
                    JoinIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString());
                    ChannelIdx = Int32.Parse(tvNetwork.SelectedNode.Tag.ToString());
                    Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].MeterID = Int32.Parse(((ToolStripMenuItem)sender).Tag.ToString());

                    Caption = cConst.JOIN_ENERGY_TYPE[Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].EnergyType] + " (";
                    Idx = cMain.GetMeterIndexByID(Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].MeterID);
                    if ((Idx >= 0) && (Idx < cMain.MeterList.Length))
                        Caption += cConst.METER_CAPTION_CAP + ": " + cMain.MeterList[Idx].Caption + "; ";
                    else Caption += cConst.METER_CAPTION_CAP + ": " + cConst.METER_NONAME_CAP + "; ";
                    Caption += cConst.CHANNEL_CAPTION_CAP + ": " + (Objects[ObjIdx].Device[DevIdx].Join[JoinIdx].Channel[ChannelIdx].ID + 1).ToString() + ")"; ;
                    tvNetwork.SelectedNode.Text = Caption;
                    break;
            }
        }
        private void tvNetwork_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (!FormLoaded)
            {
                FormLoaded = true;    

                ChildNodeCheckStateChange(e.Node, e.Node.Checked);
                TreeNode Node = e.Node;  
                while ((Node.Parent != null) && (Node.Checked))
                {
                     Node.Parent.Checked = Node.Checked;
                     Node = Node.Parent;
                }
                FormLoaded = false;
            }
        }
        private void ChildNodeCheckStateChange(TreeNode ParentNode, Boolean Checked)
        {
            for (Int32 i = 0; i < ParentNode.Nodes.Count; i++)
            {
                ParentNode.Nodes[i].Checked = Checked;
                if (ParentNode.Nodes[i].Nodes.Count > 0)
                    ChildNodeCheckStateChange(ParentNode.Nodes[i], Checked);
            }
        }

        private void pitmPulseMetersCount_Click(object sender, EventArgs e)
        {
            //Создать и инициализировать экземпляр формы

            int ObjIdx = Int32.Parse(tvNetwork.SelectedNode.Parent.Tag.ToString());
            int DevIdx = Int32.Parse(tvNetwork.SelectedNode.Tag.ToString());
            fSetting SettingForm = new fSetting();
            SettingForm.DialogResult = DialogResult.Cancel;
            if (Objects[ObjIdx].Device[DevIdx].DeviceNumOffset < 0)
                SettingForm.FillPulseMeterCount(0);
            else
                SettingForm.FillPulseMeterCount(Objects[ObjIdx].Device[DevIdx].DeviceNumOffset);

            if (SettingForm.ShowDialog(this) == DialogResult.OK)
            {
               

                Objects[ObjIdx].Device[DevIdx].DeviceNumOffset = SettingForm.GetPulseMetersCount();
            }
        }
    }
}
